package com.yunlongn.common.json.jackson.serializer;

import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonSerializer;
import com.fasterxml.jackson.databind.SerializerProvider;
import com.yunlongn.common.json.jackson.factory.AbstractJsonDeserializer;
import com.yunlongn.common.json.jackson.factory.AbstractJsonSerializer;
import com.yunlongn.common.json.util.DateFormatException;
import com.yunlongn.common.json.util.DateFormatUtils;
import com.yunlongn.common.json.util.StringUtils;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 日期序列化
 * @author Yun
 * @since 20210902
 */
public class DateSerializer extends AbstractJsonSerializer<Date> {

    private SimpleDateFormat sdf;

    public DateSerializer(String datePattern) {
        if (StringUtils.isNullOrEmpty(datePattern)) {
            this.sdf = null;
            return;
        }
        this.sdf = new SimpleDateFormat(datePattern);
    }
    public DateSerializer() {
    }

    @Override
    public void serialize(Date date, JsonGenerator jsonGenerator, SerializerProvider serializerProvider) throws IOException {
        if (sdf == null) {
            jsonGenerator.writeNumber(date.getTime());
        } else {
            jsonGenerator.writeString(sdf.format(date));
        }
    }

}

